package com.hongyi.service.Impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hongyi.dto.PostDto;
import com.hongyi.pojo.Post;
import com.hongyi.service.PostService;
import com.hongyi.utils.http.HttpUtils;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: hongyi
 * @CreateTime: 2024-10-21
 */


@Service
public class PostServiceImpl implements PostService {
    // private final OkHttpClient client = new OkHttpClient();
    private final ObjectMapper objectMapper = new ObjectMapper(); // 可以在这里实例化 ObjectMapper

    @Override
    public PostDto getPostById(int id) throws IOException {
        String host = "https://jsonplaceholder.typicode.com";
        String path = "/posts/" + id;
        String url = host + path; //
        String method = "GET";


        // 构造空的headers 和 headers 因为接口不需要他们
        Map<String, String> headers = new HashMap<>();
        Map<String, String> querys = new HashMap<>();
        // 调用doGet方法，传入url和method，返回响应体
        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            if (response.getStatusLine().getStatusCode() == 200) {
                // 将响应体转换为字符串
                String json = EntityUtils.toString(response.getEntity());
                // 将 JSON 字符串转换为 Post 对象
                Post post = objectMapper.readValue(json, Post.class);
                PostDto postDto = new PostDto();
                BeanUtils.copyProperties(post, postDto);
                return postDto;
            } else {
                throw new RuntimeException("请求失败，状态码：" + response.getStatusLine().getStatusCode());
            }

        } catch (Exception e) {
            throw new RuntimeException("请求失败: " + e.getMessage(), e);

        }
    }


}
